/**
 * 
 */
(function() {
	var CTR = window.CTR || {};
	window.CTR = CTR;

	CTR.Product={};
	window.Product=CTR.Product;
	Product.requestUrl={
			comment:$.getRootPath()+'/getScomments'
			,property:$.getRootPath()+'/getPageProperty'
		};
	Product.Property={};
	Product.Property.data={};
	Product.Property.getProperty=function(t){
        //此处修改
//		var propertyData=$.parseJSON($("#propertyData").text());
//		console.log(propertyData)
//		Product.Property.data=propertyData;
//		Product.Property.formatOpt(propertyData.rows[0].property,t);
//		Product.Property.analyse(propertyData.rows[0].detail);
		var data={goodsId:$("#goodid").val(),categoryId:$("#goodsCategoryid").val()};
		$.ajax({
			url: Product.requestUrl.property,
			type: "POST",
			dataType: "json",
			data:data,
			success: function(json) {
				Product.Property.data=json;
				Product.Property.formatOpt(json.rows[0].property,t);
				console.log(json.rows[0].detail);
				Product.Property.analyse(json.rows[0].detail);
			},
			error: function(json) {
				console.log(json);
			}
		});
	};
	Product.Property.getPropertyByCata=function(goodsid,categoryid){
        //此处修改
		var data={goodsId:goodsid,categoryId:categoryid};
		$.ajax({
			url: Product.requestUrl.property,
			type: "POST",
			dataType: "json",
			data:data,
			success: function(json) {
				Product.Property.data=json;
				Product.Property.formatOpt(json.rows[0].property,2);
				Product.Property.analyse(json.rows[0].detail);
			},
			error: function(json) {
			}
		});
	};
	Product.Comment={};
	Product.Comment.get=function(p){
		var t=$('.m-detail-t1 li').index($('.m-detail-t1 li.select'));
		p=typeof p=='undefined'?1:p;
//		此处修改
		var data={page:p,type:t,id:$("#goodsId").val()};
		CTR.showLoad($('.product_rate_content').eq(t));
		$.ajax({
			url: Product.requestUrl.comment,
			type: "POST",
			dataType: "json",
			data:data,
			success: function(json) {
			console.log(json)
				Product.Comment.show(json.rows,t);
				CTR.paginator($('.pagin')[0],json.sumPage,p,Product.Comment.get);
			},
			error: function(json) {
				
			}
		});
	};
	Product.Comment.show=function(d,t){
		var resultCtn=$('.product_rate_content').eq(t);
		var str='';
		$(d).each(function(k,v){
			str+='<dl><dt><a href="javascript:void(0);"><img src="'+v.memberImage+'" width="50" height="50"> </a><br/>'
				+v.uid+'</dt><dd><div class="m-detail-c">';
			for (i=0;i<parseInt(v.level);i++){
				str+='<img src="images/star.png" width="15" height="15"/>';
			}
			str+='<br/>'+v.comment+'</div><div class="m-detail-time">'+v.regDate+'<br/>'
				//+'<a href="#" class="btn btn-23 btn-theme1">有用(11)</a>'
				+'</div></dd></dl>';
		});
		resultCtn.html(str);
	};
	Product.checkData=function(){
		var result=true;
		if ($('.property_option span.select').length!=Product.Property.data.rows[0].property.length){
			result=false;
		}
		return result;
	};
	
	Product.addToCart=function(p){
//	    此处修改
		var flag=$("#psSpan").attr("validata");
		if(flag=="false"){
			showMsg('对不起，该地区无货，不能购买');
			return ;
	    }
		
		
		if (Product.checkData()){
			var goodsId=$("#goodsId");//商品id
			var checkPrice=$("#checkPrice");//属性id
			var buyCount=$("#buyCount");//购买数量
			var param={};
		   param.id=goodsId.val();
		   param.code=Product.Property.selected;
		   param.buyCount=buyCount.val();
		   $.ajax({
			   type:"post",
			   url:$.getRootPath()+"/saveIntoCar",
			   data:param,
			   success:function(json){
				   if(json.code=="true"){
					   showMsg('添加购物车成功');
				   }else{
					   showMsg("添加购物车失败");
					   }
			   }
		   })
		}else{
			showMsg("请选择好属性");
		}
	};
	Product.buy=function(p){
		if (Product.checkData()){
			console.log(Product.Property.selected);
		}else{
			showMsg('请先选择商品属性！');
		}
	};
	Product.Property.getPrice=function(p){
		var formatData=new Object(),layerCount=0;
		var existChild=function(s,d){
			var result=false;
			$(s).each(function(k,v){
				if (typeof v.id!='undefined'&&v.id==d.id){
					result=true;
				}
			});
			return result;
		};
		var findChild=function(pId){
			for (i=0;i<curLayer.length;i++){
				if (curLayer[i].id==pId){
					return curLayer[i];
				}
			}
		};
		var formatArr=function(c,p){
			$(c).each(function(k,v){
				if (typeof p!=='undefined'){
					if (!formatData[p])formatData[p]=new Array();
					var result={name:v.name,id:v.id};
					if (typeof p!=='undefined'){
						result.parent=p;
					}
					if (!existChild(formatData[p],v)){
						formatData[p].push(result);
					}
				}
				if (v.childrens&&v.childrens.length>0){
					formatArr(v.childrens,v.id);
					if (k==0){
						layerCount++;
					}
				}
			});
		};
		if ($('.property_option span.select').length==p.rows[0].property.length){
			formatArr(p.rows[0].detail);
			var curLayer=p.rows[0].detail;
			$('.property_option span.select').each(function(){
				curLayer=findChild($(this).attr('property_id'));
				if (curLayer.childrens)curLayer=curLayer.childrens;
			});
			
			$('.product_price').html('￥'+curLayer.money);
		}
	};
	//repertory data cache
	Product.Property.repertory=new Array();
	Product.Property.formatOpt=function(p,s){
		s=typeof s=='undefined'?1:s;
		var str='';
		$(p).each(function(k,v){
			str+=s==1?('<li><div class="c_l">'+v.name+'：</div><div class="c_r">'):('<div class="table-sm-2"><label class="label-control col-sm-4 f-tal">'+v.name+'：</label>');
			$(v.children).each(function(l,w){
				str+=s==1?('<span class="chooseItem" property_id="'+w.id+'">'+w.name+'</span> '):('<input value="'+w.id+'" type="checkbox"'+(w.checked?' checked="checked"':'')+' name="checkbox"/><label class="label-control col-sm-14 f-tal">&nbsp;'+w.name+'</label>');
			});
			str+=s==1?'</div></li>':'</div>';
		});
		$('.property_option').html(str);
		//Product.Property.syncOpt();
	};
	Product.Property.analyse=function (j){
		var formatData=new Object();
		var childLength=0;
		var layerCount=0;
		var render=function(o){
			var str='<table>';
			$(o).each(function(k,v){
				str+='<tr id="'+v.id+'"><td width="60">&nbsp;'+v.name+'&nbsp;</td><td>';
				if (v.childrens&&v.childrens.length>0){
					str+=render(v.childrens);
				}else{
					str+='<input name="money" type="text" value="'+v.money+'"/></td><td><input name="repertory" type="text" value="'+v.repertory+'"/>';
					//save loaded data;
				}
				str+='</td></tr>';
			});
			str+='</table>';
			return str;
		};
		$('.property_ctn').html(render(j));
		Product.Property.genRepertoryTableHead();
		Product.Property.setRepertoryTable();
		Product.Property.saveRepertoryVal();
		var countChild=function (o){
			childLength+=formatData[o.id].lenght;
		};
		var countLayer=function(o){
			this.layerCount++;
			if (o.childrens&&o.childrens.length>0){
				countLayer(o.childrens);
			}
		};
	};
	/**
	 * save repertory data
	 */
	Product.Property.saveRepertoryVal=function(){
		$('.property_ctn').find('input[name="money"]').each(function(){
			var o=$(this);
			var parentArr=new Array();
			var list=$(this).parents('tr[id]');
			for (i=list.length;i>0;i--){
				parentArr.push(list.eq(i-1).attr('id'));
			}
			var pid=parentArr.join(",");
			Product.Property.repertory.push({money:o.attr('pid',pid).val(),pid:pid,repertory:o.parent('td').next().find('input').attr('pid',pid).val()});
		});
	};
	/**
	 * load saved repertory data
	 */
	Product.Property.restoreRepertoryVal=function(){
		$(Product.Property.repertory).each(function(k,v){
			var parentArr=v.pid.split(',');
			var selector='';
			for (i=0;i<parentArr.length;i++){
				selector+='tr[id="'+parentArr[i]+'"] ';
			}
			console.log(selector);
			$('.property_ctn').find(selector+'input[name="money"]').val(v.money);
			$('.property_ctn').find(selector+'input[name="repertory"]').val(v.repertory);
		});
	};
	Product.Property.setRepertoryTable=function(){
		$('.property_ctn>table>tbody>tr>td:last-child').attr('colspan',100);
		$('.property_ctn table table tr td:last-child').addClass('no_right');
		$('.property_ctn table table tr:last-child>td').addClass('no_bottom');
	};
	Product.Property.genRepertoryTableHead=function(){
		var repertoryHead='<thead>';
		$('.property_option .table-sm-2').each(function(k,v){
			var propName=$(this).find('label:first').text();
			repertoryHead+='<th width="60">'+propName.substr(0,propName.length-1)+'</th>';
		});
		$('.property_ctn>table>tbody').before(repertoryHead+'<th>加价</th><th>库存</th></thead>');
	};
	Product.Property.syncOpt=function(o){
		var tempProp=new Array();
		var curDimension=1;
		var totalLayer=1;
		var selector='';
		var genTable=function(p){
			var str="<table><tbody>";
			$(p).each(function(){
				propText=$(this).next('label').find('input').length==1?$(this).next('label').find('input').val():$(this).next('label').text();
				str+='<tr id="'+$(this).val()+'"><td width="60">&nbsp;'+propText+'&nbsp;</td><td class="sub"></td></tr>';
			});
			str+='</tbody></table>';
			return $(str);
		};
		var repertoryHead='<thead>';
		$('.property_option .table-sm-2').each(function(k,v){
			if (curDimension==1)$('.property_ctn').html('');
			if ($(this).find('input:checkbox:checked').length==0)return;
			var propName=$(this).find('label:first').text();
			repertoryHead+='<th width="60">'+propName.substr(0,propName.length-1)+'</th>';
			var table=genTable($(this).find('input:checkbox:checked'));
			selector='';
			for (i=1;i<curDimension;i++){
				selector+='>table>tbody>tr>td.sub';
			}
			$('.property_ctn'+selector).append(table);
			curDimension++;
		});
		$('.property_ctn'+selector+' td.sub').append('<input name="money" type="text" regtype="price"/>').after('<td><input name="repertory" type="text"/></td>');
		$('.property_ctn>table>tbody').before(repertoryHead+'<th>加价</th><th>库存</th></thead>');
		Product.Property.setRepertoryTable();
		Product.Property.restoreRepertoryVal();
	};
	
	
	//此处修改
	Product.Property.formatPara=function(){
		var result=new Array();
		var findChild=function(o){
			var obj=new Array();
			o.children('tbody').children('tr').each(function(k,v){
				var o=$(this);
				var tmp={name:$.trim(o.find('td:first').text()),id:o.attr('id')};
				if (o.children('td').children('table').length>0){
					tmp.childrens=findChild(o.children('td').children('table'));
				}else{
					tmp.money=o.find('input[name="money"]').val();
					tmp.repertory=o.find('input[name="repertory"]').val();
				}
				obj.push(tmp);
			});
			return obj;
		};
		return ({tree:findChild($('.property_ctn>table'))});
	};
})();